package com.aiti.lulian.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.*;
import com.aiti.lulian.entity.excel.ProductPageExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.IEnterpriseProductAttrService;
import com.aiti.lulian.service.Product0428Service;
import com.aiti.lulian.vo.Product0428DetailVo;
import com.aiti.lulian.vo.Product0428ListVo;
import com.aiti.lulian.vo.ProductAttrVo;
import com.aiti.lulian.vo.ProductPageVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-04-28 11:31
 **/
@RestController
@RequestMapping("enterpriseProduct")
@Slf4j
@Api(tags = "企业产品属性管理")
public class EnterpriseProductController extends WebController<ProductAttrVo> {

    @Autowired
    private IEnterpriseProductAttrService productAttrService;
    @Autowired
    private Product0428Service productService;

    @PostMapping("/saveProductAttr")
    @ApiOperation("保存产品属性")
    public Message saveProductAttr(@RequestBody ProductAttrParamDto dto) {
        try {
            productAttrService.saveProductAttr(dto, findUserId(), findUserName());
        }catch (Exception e) {
            log.error("【保存产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("保存失败");
        }
        return Message.success();
    }

    @PostMapping("/pageList")
    @ApiOperation("分页查询产品属性")
    public Message pageList(@RequestBody ProductAttrQueryParamDto dto) {
        try {
            return Success(productAttrService.pageList(dto));
        }catch (Exception e) {
            log.error("【分页查询产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }

    @PostMapping("/updateProductAttr")
    @ApiOperation("修改产品属性")
    public Message updateProductAttr(@RequestBody ProductAttrParamDto dto) {
        try {
            productAttrService.updateProductAttr(dto, findUserId(), findUserName());
        }catch (Exception e) {
            log.error("【修改产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("修改失败");
        }
        return Message.success();
    }

    @PostMapping("/deleteProductAttr")
    @ApiOperation("删除产品属性")
    public Message deleteProductAttr(@RequestBody List<String> baseIdList) {
        try {
            productAttrService.deleteProductAttr(baseIdList, findUserId(), findUserName());
        }catch (Exception e) {
            log.error("【删除产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("删除失败");
        }
        return Message.success();
    }

    @GetMapping("/getProductAttrType")
    @ApiOperation("根据主键查询产品属性")
    public Message getProductAttrType(@RequestParam("attrId") String attrId) {
        try {
            return Success(productAttrService.getProductAttrById(attrId));
        }catch (Exception e) {
            log.error("【根据主键查询产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }

    @GetMapping("/getEnterpriseProductAttr")
    @ApiOperation("根据企业id查询产品属性")
    public Message getEnterpriseProductAttr(@RequestParam("enterpriseId") String enterpriseId) {
        try {
            return Success(productAttrService.getEnterpriseProductAttr(enterpriseId));
        }catch (Exception e) {
            log.error("【根据企业id查询产品属性异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }

    @GetMapping("/getAttrTypeList")
    @ApiOperation("根据产品属性id查询产品属性类型")
    public Message getAttrTypeList(@RequestParam("productAttrId") String productAttrId) {
        try {
            return Success(productAttrService.getAttrTypeList(productAttrId));
        }catch (Exception e) {
            log.error("【根据产品属性id查询产品属性类型异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }

    //-------------------------------------------产品相关接口-------------------------------------------------

    @PostMapping("/saveProduct")
    @ApiOperation("保存产品")
    public Message saveProduct(@RequestBody Product0428ParamDto dto) {
        try {
            productService.saveProductInfo(dto, findUserId());
        }catch (Exception e) {
            log.error("【保存产品异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("保存失败");
        }
        return Message.success();
    }

    @PostMapping("/updateProduct")
    @ApiOperation("修改产品")
    public Message updateProduct(@RequestBody Product0428ParamDto dto) {
        try {
            productService.updateProductInfo(dto, findUserId());
        }catch (Exception e) {
            log.error("【修改产品异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("修改失败");
        }
        return Message.success();
    }

    @PutMapping("/updateVisibleBatch")
    @ApiOperation("批量上下架产品")
    public Message updateVisibleBatch(@RequestBody Product0428ParamDto dto) {
        try {
            List<String> baseIds = dto.getBaseIds();
            if (baseIds == null || baseIds.isEmpty()) {
                return Message.fail("请至少选择一个产品");
            }
            Integer isVisible = dto.getIsVisible();
            if (!(isVisible == 0 || isVisible == 1)) {
                return Message.fail("操作无效");
            }
            productService.updateVisibleBatch(dto, findUserId());
        } catch (Exception e) {
            log.error("【批量上下架产品异常】:{}", ExceptionUtil.stacktraceToString(e));
            if (e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("批量上下架产品失败");
        }
        return Message.success("操作成功");
    }

    @GetMapping("/getProductInfo")
    @ApiOperation("根据产品id查询产品信息")
    public Message getProductInfo(@RequestParam("baseId") String baseId) {
        try {
            return Success(productService.getProductInfo(baseId));
        }catch (Exception e) {
            log.error("【根据产品id查询产品信息异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }

    @PostMapping("/productList")
    @ApiOperation("分页查询产品")
    public Message productList(@RequestBody ProductQueryParamDto dto) {
        try {
            return Success(productService.productPageList(dto));
        }catch (Exception e) {
            log.error("【分页查询产品异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }
    @GetMapping("/productPage")
    @ApiOperation("分页查询产品")
    public Message pageList(Product0428ParamListDto dto) {
        Page<ProductAttrVo> page = this.startPage();
        PageResult<Product0428ListVo> pageResult = productService.productPage(page, dto);
        return Message.success(pageResult);
    }

    @GetMapping("/productPageNew")
    @ApiOperation("分页查询产品--修改")
    public Message pageListNew(Product0428ParamListDto dto) {
        Page<ProductAttrVo> page = this.startPage();
        PageResult<Product0428ListVo> pageResult = productService.productPageNew(page, dto);
        return Message.success(pageResult);
    }

    @GetMapping("/productDetail")
    @ApiOperation("查询产品详情")
    public Message pageList(@RequestParam("productId") String productId, @RequestParam("paramId") String paramId) {
        Product0428DetailVo product0428DetailVo = productService.productDetail(productId, paramId);
        return Message.success(product0428DetailVo);
    }

    @PostMapping("/updateProductSort")
    @ApiOperation("修改产品排序")
    public Message updateProductSort(@RequestBody ProductSortDto dto) {
        try {
            productService.updateProductSort(dto);
        }catch (Exception e) {
            log.error("【修改产品排序异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("修改失败");
        }
        return Message.success();
    }

    /**
     * 新版名片小程序
     */
    @ApiOperation("后台导出产品信息列表")
    @GetMapping("/productList/export")
    public void exportProductList(HttpServletResponse response, ProductQueryParamDto dto) throws IOException {
        dto.setPageNum(1).setPageSize(9999);
        PageResult<ProductPageVo> productPageVoPageResult = productService.productPageList(dto);
        List<ProductPageVo> productList = productPageVoPageResult.getContent();
        List<ProductPageExport> productPageExportList = productList.stream().map(i -> {
            ProductPageExport productPageExport = new ProductPageExport();
            BeanUtils.copyProperties(i, productPageExport);
            productPageExport.setStatus(i.getIsVisible() == 1 ? "已上架" : "未上架");
            return productPageExport;
        }).collect(Collectors.toList());

        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("产品数据列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + ".xlsx\";" + " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        OutputStream outputStream =  response.getOutputStream();
        EasyExcel.write(outputStream, ProductPageExport.class)
                .sheet("产品数据列表")
                .registerWriteHandler(new HeaderStyleHandler())
                .doWrite(productPageExportList);

        // 关闭流资源
        if (outputStream != null) {
            outputStream.close();
        }
    }

    @ApiOperation("下载产品数据导入模版")
    @GetMapping("/importTemplate/download")
    public void downloadProductImportTemplate(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            // 设置文件路径
//            String filePath = "/Volumes/WorkDisk/ShanDongZhiZao/workspace/template/产品数据导入模版.xlsx";
            String filePath = "/home/services/template/产品数据导入模版.xlsx";
//            String filePath = "C:\\Users\\Administrator\\Desktop\\产品数据导入模版.xlsx";
            File downloadFile = new File(filePath);

            // 设置文件名（响应头中的推荐文件名）
            String fileName = "产品数据导入模版.xlsx";

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 设置文件大小
            response.setContentLength((int) downloadFile.length());

            // 通过文件输入流读取文件内容
            fileInputStream = new FileInputStream(downloadFile);

            // 通过ServletOutputStream将文件内容写入HTTP响应
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            logger.error("下载产品数据导入模版异常：===》" + e);
        }
    }

    @ApiOperation("批量导入产品")
    @PostMapping("/importBatch")
    public Message importProductBatch(@RequestPart("file") MultipartFile file, String userId, String enterpriseId) {
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("用户信息无效");
            }
            if (file == null) {
                return Fail("请上传文件");
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            if (! ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)
                    && originalFilename != null && originalFilename.endsWith(".xlsx"))) {
                return Fail("请上传xlsx格式的文件");
            }
            return productService.importBatch(file, userId, enterpriseId);
        } catch (Exception e) {
            logger.error("导入异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @GetMapping("/product-recommendation")
    @ApiOperation("小程序获取产品推荐数据")
    public Message productRecommendation(@RequestParam("enterpriseId") String enterpriseId) {
        try {
            return Success(productService.productRecommendation(enterpriseId));
        }catch (Exception e) {
            log.error("【查询产品推荐异常】:{}", ExceptionUtil.stacktraceToString(e));
            if(e instanceof BusinessException) {
                return Fail(e.getMessage());
            }
            return Fail("查询失败");
        }
    }
}
